package com.jinkaimen.kqb.ui.fragment;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.Toast;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.ui.base.BaseFragment;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.constant.Constants;
import com.jinkaimen.kqb.ui.activity.LoginActivity;
import com.jinkaimen.kqb.ui.activity.addmerchant.RegisterAddActivity;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.utils.TbsLog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import de.greenrobot.event.EventBus;

import static android.app.Activity.RESULT_OK;


public class HomeFragment extends BaseFragment {
    private BridgeWebView webView;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 2;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {

    }

    @Override
    protected View initContentView() {
        return LayoutInflater.from(mContext).inflate(R.layout.frag_home, null);
    }

    @Override
    protected void initChildView() {
        webView = findViewById(R.id.x5webview);

        webView.setWebViewClient(new MyWebViewClient(webView));
//        doWebView();
        setWebChromeClient();
        //     webView.setDefaultHandler(new myHadlerCallBack());
        String token = SharedPreferencesUtils.getString(Constants.TOKEN, "");
        webView.loadUrl("http://hss.qianbaojiajia.com/earn/" + Constants.TOKEN_TITLE + token);
        String clientid = SharedPreferencesUtils.getString(Constants.CID, "");
        Log.e("token = ", token);
        Log.e("clientid = ", clientid);

        //必须和js函数名字一致，注册好具体执行回调函数，类似java实现类。
        webView.registerHandler("aadMerchant", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                ActivityUtils.startActivity(mContext, RegisterAddActivity.class);
            }
        });

        webView.registerHandler("mineMerchant", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                ActivityUtils.startActivity(mContext, RegisterAddActivity.class);
            }
        });

        webView.registerHandler("goLogin", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                ActivityUtils.startActivity(mContext, LoginActivity.class);
            }
        });

        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(mContext.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(mContext.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(mContext.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();
//        if (mIntentUrl == null) {
//            webView.loadUrl(mHomeUrl);
//        } else {
//            webView.loadUrl(mIntentUrl.toString());
//        }
        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));


    }

    private void doWebView() {
        webView.setWebChromeClient(new WebChromeClient() {

            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }


            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = fileChooserParams.createIntent();
                try {
                    startActivityForResult(intent, REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e) {
                    uploadMessage = null;
                    Toast.makeText(mContext, "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                    return false;
                }
                return true;
            }

            //For Android 4.1 only
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

        });
    }

    @Override
    protected void setChildViewListener() {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected boolean hasEvent() {
        return true;
    }

    @Override
    protected void onEvent(int eventCode, Object data) {
        super.onEvent(eventCode, data);
        switch (eventCode) {
            case EventCode.HSY_REQUEST_CODE_EXPIRE://登陆超时

                break;

        }
    }

    /**
     * 自定义的WebViewClient
     */
    public class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        String token = SharedPreferencesUtils.getString(Constants.TOKEN, "");
        webView.loadUrl("http://hss.qianbaojiajia.com/earn/" + Constants.TOKEN_TITLE + token);
    }

    public void onKeyDown(KeyEvent event) {
        if (webView.canGoBack()) {
            webView.goBack(); //goBack()表示返回WebView的上一页面
        } else {
            EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_FINISH_ACTIVITY, event));
        }
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            if (requestCode == REQUEST_SELECT_FILE) {
//                if (uploadMessage == null)
//                    return;
//                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
//                uploadMessage = null;
//            }
//        } else if (requestCode == FILECHOOSER_RESULTCODE) {
//            if (null == mUploadMessage)
//                return;
//            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
//            // Use RESULT_OK only if you're implementing WebView inside an Activity
//            Uri result = intent == null || resultCode != mContext.RESULT_OK ? null : intent.getData();
//            mUploadMessage.onReceiveValue(result);
//            mUploadMessage = null;
//        } else {
//            Toast.makeText(mContext, "Failed to Upload Image", Toast.LENGTH_SHORT).show();
//        }
//    }


    private ValueCallback<Uri> mUploadFile;
    /**
     * 拍照/选择文件请求码
     */
    private static final int REQUEST_UPLOAD_FILE_CODE = 12343;

    private void setWebChromeClient() {
        if (null != webView) {
            webView.setWebChromeClient(new WebChromeClient() {
                // Andorid 4.1+
                public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
                    openFileChooser(uploadFile);
                }

                // Andorid 3.0 +
                public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {
                    openFileChooser(uploadFile);
                }

                // Android 3.0
                public void openFileChooser(ValueCallback<Uri> uploadFile) {
                    // Toast.makeText(WebviewActivity.this, "上传文件/图片",Toast.LENGTH_SHORT).show();
                    mUploadFile = uploadFile;
                    startActivityForResult(Intent.createChooser(createCameraIntent(), "Image Browser"), REQUEST_UPLOAD_FILE_CODE);
                }
            });
        }
    }

    private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//拍照
        //=======================================================
        Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);//选择图片文件
        imageIntent.setType("image/*");
        //=======================================================
        return cameraIntent;
    }


    /**
     * 处理拍照/选择的文件
     */
    private File handleFile(File file) {
        DisplayMetrics dMetrics = getResources().getDisplayMetrics();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;
        System.out.println("  imageWidth = " + imageWidth + " imageHeight = " + imageHeight);
        int widthSample = (int) (imageWidth / (dMetrics.density * 90));
        int heightSample = (int) (imageHeight / (dMetrics.density * 90));
        System.out.println("widthSample = " + widthSample + " heightSample = " + heightSample);
        options.inSampleSize = widthSample < heightSample ? heightSample : widthSample;
        options.inJustDecodeBounds = false;
        Bitmap newBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        System.out.println("newBitmap.size = " + newBitmap.getRowBytes() * newBitmap.getHeight());
        File handleFile = new File(file.getParentFile(), "upload.png");
        try {
            if (newBitmap.compress(Bitmap.CompressFormat.PNG, 50, new FileOutputStream(handleFile))) {
                System.out.println("保存图片成功");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return handleFile;

    }

    //最后在OnActivityResult中接受返回的结果
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_UPLOAD_FILE_CODE && resultCode == RESULT_OK) {
            if (null == mUploadFile) {
                return;
            }
            Uri result = (null == data) ? null : data.getData();
            if (null != result) {
                ContentResolver resolver = mContext.getContentResolver();
                String[] columns = {MediaStore.Images.Media.DATA};
                Cursor cursor = resolver.query(result, columns, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(columns[0]);
                String imgPath = cursor.getString(columnIndex);
                System.out.println("imgPath = " + imgPath);
                if (null == imgPath) {
                    return;
                }
                File file = new File(imgPath);
                //将图片处理成大小符合要求的文件
                result = Uri.fromFile(handleFile(file));
                mUploadFile.onReceiveValue(result);
                mUploadFile = null;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
